﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GameBasicsLibrary.Contracts;
using GameBasicsLibrary.MathUtility;

namespace GameBasicsLibrary.Constraining
{
    public class ChildTransform:ITransformable
    {

        #region Properties

        public Vector3 Position { get; set; }
        public Vector3 Rotation { get; set; }
        public Vector3 Scale { get; set; }
        public Vector3 LocalPosition { get; set; }
        public Vector3 LocalRotation { get; set; }
        public Vector3 LocalScale { get; set; } 
        public Vector3 OffsetPosition { get; private set; }
        ITransformable Parent;
        public CModel ChildModel { get; private set; }

        public Vector3 Forward {
            get
            {
                return calculateForward(Parent.Rotation + this.Rotation);
            }
        }
        
        #endregion Properties;

        public ChildTransform(ITransformable Parent, Vector3 OffsetPosition, CModel ChildModel)
        {
            this.Parent = Parent;
            this.OffsetPosition = OffsetPosition;
            this.ChildModel = ChildModel;
        }

        public void Update()
        {
            //Matrix Trans=Matrix.CreateTranslation(OffsetPosition)*Matrix.CreateRotationY((float)(MathHelper.ToRadians(Parent.Rotation.Y)));
            //ChildModel.Position = Parent.Position + Trans.Translation;

            Vector3 ChildPos = this.Position + this.OffsetPosition;
            Vector3 parRot = Converter.toRadians(Parent.Rotation);
            ChildPos=Vector3.Transform(ChildPos,Matrix.CreateFromYawPitchRoll(parRot.Y,parRot.X,parRot.Z));
            ChildModel.Position = Parent.Position + ChildPos;

            ChildModel.Rotation = Parent.Rotation+this.Rotation;
        }
        public void Draw(Matrix view, Matrix projection)
        {
            ChildModel.Draw(view, projection);
        }

        public Vector3 calculateForward(Vector3 rotation)
        {
            Matrix mtxRot = Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(rotation.Y), MathHelper.ToRadians(rotation.X), MathHelper.ToRadians(rotation.Z));
            return Vector3.Transform(Vector3.Forward, mtxRot);
        }
    }
}
